package com.jifeng.sterilizer.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.jifeng.sterilizer.entity.ResponseEntity;
import com.jifeng.sterilizer.entity.SmsConfigurationEntity;
import com.jifeng.sterilizer.entity.VcodeEntity;
import com.jifeng.sterilizer.service.MemberSmsService;
import com.jifeng.sterilizer.service.VcodeService;
import com.jifeng.sterilizer.utils.GetValueUtils;
import com.jifeng.sterilizer.utils.R;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;
import java.util.Random;

@Service("memberSmsService")
public class MemberSmsServiceImpl implements MemberSmsService {

    Logger logger = LoggerFactory.getLogger(MemberSmsServiceImpl.class);

    @Autowired
    SmsConfigurationEntity configurationEntity;

    @Autowired
    VcodeService vcodeService;

    /**
     * templateCode:
     * 身份验证:SMS_194595012
     * 登录确认:SMS_194595011
     *登录异常:SMS_194595010
     * 用户注册:SMS_194595009
     * 修改密码:SMS_194595008
     * 信息变更:SMS_194595007
     * @param params
     * @return
     */
    @Override
    public R sendMsg(Map<String, Object> params) {
        String phone= (String) params.get("mobile");
        String type= (String) params.get("type");
        String templateCode="";
        boolean phoneLegal = GetValueUtils.isPhoneLegal(phone);
        if (!phoneLegal&& StringUtils.isEmpty(phone)){
            return R.error(400,"手机号格式错误！");
        }
        if(type.equals("0")){
            templateCode="SMS_194595009";
        }else if (type.equals("1")){
            templateCode="SMS_194595008";
        }
        // 获取随机验证码
        String vcode = getRandCode(configurationEntity.getRandCode());
        // 配置属性
        DefaultProfile profile = DefaultProfile.getProfile(configurationEntity.getRegionId(), configurationEntity.getAccessKeyId(), configurationEntity.getAccessSecret());
        // 客户端
        IAcsClient client = new DefaultAcsClient(profile);
        // 创建请求
        CommonRequest request = new CommonRequest();
        // 发送请求的方法
        request.setMethod(MethodType.POST);
        // 发送请求的域名
        request.setDomain(configurationEntity.getDomain());
        //系统规定参数
        request.setAction(configurationEntity.getAction());
        // 版本信息  已经固定  不能进行更改
        request.setVersion(configurationEntity.getVersion());
        /*
          必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,
         批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；
         发送国际/港澳台消息时，接收号码格式为国际区号+号码，如“85200000000”
         */
        request.putQueryParameter("PhoneNumbers", phone);
        // 签名
        request.putQueryParameter("SignName", configurationEntity.getSignName());
        // 阿里云控制台模板编号
        request.putQueryParameter("TemplateCode", templateCode);
        // 模板内需要填充参数信息
        request.putQueryParameter("TemplateParam", "{\"code\":"+"'"+vcode+"'"+"}");
        // regionId 区域id
        request.putQueryParameter("RegionId", configurationEntity.getRegionId());
        try {
            CommonResponse response = client.getCommonResponse(request);
            ResponseEntity responseEntity = new ResponseEntity();
            responseEntity.setMessage(GetValueUtils.getPhoneStr(response.getData(),"Message"));
            responseEntity.setRequestId(GetValueUtils.getPhoneStr(response.getData(),"RequestId"));
            responseEntity.setCode(GetValueUtils.getPhoneStr(response.getData(),"Code"));
            VcodeEntity vcodeEntity = new VcodeEntity();
            vcodeEntity.setAccount(phone);
            vcodeEntity.setCode(vcode);
            vcodeService.save(vcodeEntity);
            return R.ok();
        } catch (Exception e) {
            return R.error(400,"失败！");
        }
    }

    // 获取随机验证码
    @Override
    public String getRandCode(int digits) {
        StringBuilder sBuilder = new StringBuilder();
        Random rd = new Random(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        for (int i = 0; i < digits; i++) {
            sBuilder.append(rd.nextInt(9));
        }
        return sBuilder.toString();
    }
}
